# -*- coding: utf-8 -*-
from datetime import datetime
from django import forms

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db

from base.models import ETeacher, School, ClassProperty, OneClass, ETeacherHistory
from base.util.decorators import render_to, login_required, admin_required
import logging

@login_required
@render_to('eteacher/list.html')
def list(request):
    query = ETeacher.gql('order by first_name ASC')
    eteachers = query.fetch(100)
    return {'eteachers': eteachers}

class ETeacherForm(djangoforms.ModelForm):
    class Meta:
        model = ETeacher
        exclude = ('id', 'not_available_times')

#    def clean(self):
#        cleaned_data = self.cleaned_data
#        name = cleaned_data.get('name')
#        if ETeacher.is_existed(name):
#            raise forms.ValidationError(u'You already have the same school\'s name')
#        return cleaned_data

@admin_required
@render_to('eteacher/form.html')
def create(request):
    form = ETeacherForm()
    if request.method == 'POST':
        form = ETeacherForm(request.POST)
        if form.is_valid():
            eteacher = form.save(commit=False)
            eteacher.put()
            return eteacher.get_absolute_url
    return {'form': form}

@admin_required
@render_to('eteacher/detail.html')
def detail(request, eteacher_id):
    eteacher = ETeacher.get_using_id(int(eteacher_id))
    query = db.GqlQuery("SELECT * FROM ETeacherHistory WHERE eteacher=:eteacher AND year=:year ORDER BY last_updated", eteacher=eteacher, year=2011)
    et_histories = query.fetch(100)
    return {
        'eteacher': eteacher,
        'et_histories': et_histories,
        'class_properties':  eteacher.class_properties,
        }

@admin_required
@render_to('eteacher/form.html')
def change(request, eteacher_id):
    eteacher = ETeacher.get_using_id(int(eteacher_id))
    form = ETeacherForm(request.POST or None, instance=eteacher)
    if form.is_valid():
        eteacher = form.save()
        return eteacher.get_absolute_url
    return {'form': form}

class ETeacherHistoryForm(djangoforms.ModelForm):
    class Meta:
        model = ETeacherHistory
        exclude = ('id',)

@admin_required
@render_to('eteacher/form.html')
def exchange(request, classproperty_id):
    classproperty = ClassProperty.get_using_id(int(classproperty_id))
    form = ETeacherHistoryForm(initial={
            'eteacher': classproperty.eteacher.key(),
            'school': classproperty.school.key(),
            })
    if request.method == 'POST':
        form = ETeacherHistoryForm(request.POST)
        if form.is_valid():
            et_history = form.save()
            et_history.put()
            classproperty.eteacher = et_history.eteacher
            classproperty.put()
            return classproperty.get_absolute_url
    return {
            'form': form,
            }
##
class PaymentForm(forms.Form):
    date = forms.DateField()

@admin_required
@render_to('eteacher/payment.html')
def payment(request, eteacher_id):
    form = PaymentForm()
    eteacher = ETeacher.get_using_id(int(eteacher_id))
    if request.method == 'POST':
        form = PaymentForm(request.POST)
        if form.is_valid():
            date = form.cleaned_data['date']
            year = date.year
            month = date.month
            start = datetime(year, month, 1)
            end = datetime(year, month+1, 1)

            query = db.GqlQuery(
                        "SELECT * FROM OneClass \
                        WHERE eteacher=:eteacher \
                        AND status IN :finish \
                        AND date >= :start AND date < :end",
                        eteacher=eteacher,
                        finish=['Done', 'Cancel & Pay'],
                        start=start,
                        end=end,
                        )
            oneclasses = query.fetch(100)
            pay = eteacher.pay * len(oneclasses)
            return {
                'year': year,
                'month': month,
                'form': form,
                'oneclasses': oneclasses,
                'pay': pay,
                'eteacher': eteacher,
                }

    return {
        'form': form,
        'eteacher': eteacher,
        }

@admin_required
@render_to('eteacher/schedule.html')
def schedule(request, eteacher_id):
    form = PaymentForm()
    eteacher = ETeacher.get_using_id(int(eteacher_id))
    if request.method == 'POST':
        form = PaymentForm(request.POST)
        if form.is_valid():
            date = form.cleaned_data['date']
            query = db.GqlQuery(
                        "SELECT * FROM OneClass \
                        WHERE eteacher=:eteacher \
                        AND date=:date",
                        eteacher=eteacher,
                        date=date,
                        )
            oneclasses = query.fetch(100)
            return {
                'form': form,
                'oneclasses': oneclasses,
                'date': date,
                'eteacher': eteacher,
                }

    return {
        'form': form,
        'eteacher': eteacher,
        }